package com.nineclock.common.sms;

import com.nineclock.common.utils.JsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "huanxin.sms")
@Slf4j
@Data
public class HuanxinSmsUtils {

    @Autowired
    private RestTemplate restTemplate;

    private String orgname; //区域名 见环信的控制台

    private String appname; //应用名臣 见环信的控制台

    private String url; //REST API 访问地址，如：a1.easemob.com 见环信的控制台

    private String tid; //短信模板id 是否必须：是

    private Map<String,String> tmap; //	模板变量名和变量值对。 是否必须：是

    private String extendCode; //扩展码 是否必须：否

    private String custom; //用户自定义属性，长度不超过64，回调请求中会携带此字段； 是否必须：否

    private String clientId;

    private String clientSecret;


    public void sendSMS1(String phone, String code){

        String urlMix = "http://"+ url + "/" + orgname + "/" + appname + "/sms/send";

        Map<String, Object> body = new HashMap<>();
        body.put("mobile", Arrays.asList(phone));
        body.put("tid", tid);
        body.put("tmap", tmap);

        String authorization = getToken();

        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization",authorization);

        HttpEntity<Map<String,Object>> request = new HttpEntity<Map<String,Object>>(body, headers);

        ResponseEntity<Map> entity = restTemplate.postForEntity(url, request, Map.class);
        Map result = entity.getBody();
        System.out.println(result);
    }


    public String getToken(){
        String url = "http://a1.easemob.com/1112210517085184/nineclock/token";

        Map<String,Object> body = new HashMap<>();
        body.put("grant_type", "client_credentials");
        body.put("client_id", clientId);
        body.put("client_secret", clientSecret);

        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json");

        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(body, headers);

        ResponseEntity<Map> entity = restTemplate.postForEntity(url, request, Map.class);

        Map result = entity.getBody();

        String token = (String) result.get("access_token");

        return token;
    }
}


